import {Component} from 'react';
import React from 'react';
import {connect} from 'umi';
import HighPerformTable from '@/components/HighPerformTable';
import APIS from '@/apis';
import {Button, Checkbox, Form, Input, Select, Space} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import Modal from 'antd/lib/modal/Modal';
import TextArea from 'antd/lib/input/TextArea';
import {FormInstance} from 'antd/es/form';
import FilterByCourse from "@/components/FilterByCourse";

class QuestionManager extends Component<any, any> {
  state = {
    infoVisible: false,
    editorVisible: false,
    courseList: [],
    currentSelections: [],
    willAddSelection: '',
    modalRecord: {
      id: -1,
      type: 1,
      courseName: -1,
      content: '',
      selection: [],
      answer: '',
      analyzing: '',
      selections: []
    },
    tableRender: true,
    courseId: 0,
    filter: 0,
    isCreateQuestion: false,
  }
  actionRef: any;
  formInstance?: FormInstance;

  requestGetData(
    params: {
      pageSize?: number;
      current?: number;
    },
    sorter: {
      [key: string]: 'ascend' | 'descend';
    },
    filter: {
      [key: string]: React.ReactText[];
    },
  ) {
    return APIS.ExamAPI.GetQuestionList({...params, sorter, filter, type: 0, courseId: this.state.filter});
  }

  constructor(props: any) {
    super(props);
  }

  componentDidMount() {
    APIS.CourseAPI.GetCourseList({current: 1, pageSize: 99999, state: -1}).then(res => {
      this.setState({courseList: res.data})
    }).catch(e => {
      console.error(e)
    })
  }

  refreshSelections(record: any) {
    APIS.ExamAPI.GetQuestionDetail(record)
      .then(res => this.setState({modalRecord: res, currentSelections: res.selections}))
  }

  clomns: any = [
    {
      title: '题目',
      dataIndex: 'content',
      width: "60%"
    },
    {
      title: '所属课程',
      dataIndex: 'courseName',
      hideInForm: true,
      sorter: true
    },
    {
      title: '题目类型',
      dataIndex: 'type',
      render: (record: any) => (
        record === 1 ? '选择题' : (record == 2 ? '判断题' : (record == 3 ? '填空题' : '简答题'))
      ),
    },
  ];

  render() {
    const {modalRecord, courseList} = this.state;
    return (
      <div>
        <FilterByCourse
          course={courseList}
          getValue={(value) => {
            this.setState({filter: value});
            this.actionRef?.reload();
          }}/>
        {this.state.tableRender &&
        <HighPerformTable<any>
          ref={(ref) => (this.actionRef = ref)}
          columns={this.clomns}
          requestGetData={this.requestGetData.bind(this)}
          handleChangeState={(data, state) => {
            return APIS.ExamAPI.ChangeQuestionState({id: data.id, state: state === true ? 1 : 0})
          }}
          additionOptions={[
            {
              title: '查看',
              onClick: record => {
                this.props.history.push({
                  pathname: '/teaching/exam/viewQuestion',
                  search: "id=" + record.id
                });
                // this.state.infoVisible = true
                // this.refreshSelections(record)
              },
            },
          ]}
          onClickUpdate={record => {
            this.props.history.push({
              pathname: '/teaching/exam/newQuestion',
              search: "id=" + record.id
            });
            /*  this.state.courseId = record.courseId;
              this.state.isCreateQuestion = false;
              this.state.editorVisible = true
              this.refreshSelections(record)*/
            //  this.setState({courseId:record.courseId})

            // this.setState({ isCreateQuestion: false })

          }}
          toolBarRender={() => [
            <Button key={0} type="primary"
                    onClick={() => {
                      this.props.history.push({
                        pathname: '/teaching/exam/newQuestion'
                      });
                      // this.setState({ editorVisible: true, modalRecord: null, currentSelections: [], isCreateQuestion: true })
                    }}>
              <PlusOutlined/> 新增题目
            </Button>,
          ]}
          handleDelete={id => {
            return APIS.ExamAPI.DeleteQuestion({id: id})
          }}
        />
        }

        {/* 显示题目详细信息的模态对话框 */}
        <Modal
          title={this.state.modalRecord?.content}
          visible={this.state.infoVisible}
          onCancel={() => this.setState({infoVisible: false})}
          footer={
            <Button onClick={() => this.setState({infoVisible: false})}>关闭</Button>
          }
        >
          {
            this.state.modalRecord?.type === 1 ?
              <>
                <div><b>选项:</b>{this.state.modalRecord?.selections?.map((v, i) => (
                  <div key={i} style={{marginLeft: '30px'}}>{String.fromCharCode(65 + i) + '. ' + v}</div>
                ))}</div>
                <div><b>答案:</b>{this.state.modalRecord?.answer?.split(',')?.map((v, i) => (
                  <div key={i} style={{display: 'inline-block'}}>{String.fromCharCode(65 + parseInt(v))}</div>
                ))}</div>
              </>
              :
              (
                this.state.modalRecord?.type === 2 ?
                  <>
                    <div><b>答案:</b>{this.state.modalRecord?.answer === '1' ? '正确' : '错误'}</div>
                  </>
                  :
                  <div><b>答案:</b>{this.state.modalRecord?.answer}</div>
              )
          }
          <div><b>解析:</b>{this.state.modalRecord?.analyzing}</div>
        </Modal>

        {/* 编辑信息时展示的模态对话框 */}
        <Modal
          title={modalRecord ? '编辑试题' : '新增试题'}
          visible={this.state.editorVisible}
          destroyOnClose
          maskClosable={false}
          onCancel={() => this.setState({editorVisible: false})}
          footer={(
            <div></div>
          )}
        >
          {this.state.editorVisible &&
          <Form
            ref={(ref: any) => this.formInstance = ref}
            initialValues={{
              type: this.state.modalRecord?.type,
              courseId: this.state.modalRecord?.courseName,
              content: this.state.modalRecord?.content,
              answer: this.state.modalRecord?.answer,
              analyzing: this.state.modalRecord?.analyzing,
            }}
            onFinish={values => {
              //将答案数组排序并处理为以逗号隔开的数字字符串
              var answerStr = ''
              values.answer?.sort?.().map((v: number) => {
                answerStr += v.toString() + ','
              })
              answerStr = answerStr.slice(0, answerStr.length - 1)
              //新增
              console.log(modalRecord);
              if (this.state.isCreateQuestion) {
                APIS.ExamAPI.CreateNewQuestion({
                  type: values.type,
                  courseId: this.state.courseId,
                  content: values.content,
                  selections: this.state.currentSelections,
                  answer: answerStr === '' ? values.answer : answerStr,
                  analyzing: values.analyzing,
                }).then(() => {
                  this.setState({editorVisible: false, tableRender: false})
                  this.setState({tableRender: true})
                })
              }
              //更新
              else
                APIS.ExamAPI.UpdateQuestion({
                  id: this.state.modalRecord.id,
                  type: values.type,
                  courseId: this.state.courseId,
                  content: values.content,
                  selections: this.state.currentSelections,
                  answer: answerStr === '' ? values.answer : answerStr,
                  analyzing: values.analyzing,
                }).then(() => {
                  this.setState({editorVisible: false, tableRender: false})
                  this.setState({tableRender: true})
                })
            }}
          >
            <Form.Item
              name='type'
              label='试题类型'
              rules={[{required: true, message: '请选择试题类型'}]}
            >
              <Select onChange={(e) => this.setState({modalRecord: {type: e}})}>
                <Select.Option value={1}>选择题</Select.Option>
                <Select.Option value={2}>判断题</Select.Option>
                <Select.Option value={3}>填空题</Select.Option>
                <Select.Option value={4}>简答题</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              name='courseId'
              label='所属课程'
              rules={[{required: true, message: '请选择所属课程'}]}
            >
              <Select showSearch onChange={(e: any, info: any) => {
                this.setState({courseId: parseInt(info.key)})
              }}>
                {this.state.courseList.map?.((v: any) => (
                  <Select.Option key={v.id} value={v.courseName}>
                    {v.courseName}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name='content'
              label='试题题目'
              rules={[{required: true, message: '请输入题目'}]}
            >
              <TextArea/>
            </Form.Item>

            {
              this.state.modalRecord?.type === 1 ?
                <>
                  <Form.Item label='选项' rules={[{required: true, message: '请设置选项'}]}>
                    {this.state.currentSelections?.map((v, i) => (
                      <div key={i} style={{marginLeft: '30px'}}>
                        {String.fromCharCode(65 + i) + '. ' + v}
                        <a style={{float: 'right', marginRight: '70px'}}
                           onClick={() => {
                             this.state.currentSelections.splice(i, 1)
                             this.setState({})
                           }}
                        >删除</a>
                      </div>
                    ))}
                  </Form.Item>

                  <Form.Item label='新增选项'>
                    <Input style={{width: '300px', marginRight: '10px'}}
                           onChange={e => this.setState({willAddSelection: e.target.value})}/>
                    <Button type='primary'
                            onClick={() => {
                              this.setState({currentSelections: [...this.state.currentSelections, this.state.willAddSelection]})
                            }}
                    >+</Button>
                  </Form.Item>

                  <Form.Item
                    name='answer'
                    label='正确答案'
                    rules={[{required: true, message: '请设置答案正确答案'}]}
                  >
                    <Checkbox.Group>
                      {this.state.currentSelections?.map((v, i) => (
                        <Checkbox key={i} value={i}>{String.fromCharCode(65 + i)}</Checkbox>
                      ))}
                    </Checkbox.Group>
                  </Form.Item>
                </>
                :
                (
                  this.state.modalRecord?.type === 2 ?
                    <Form.Item name='answer' label='正确答案' rules={[{required: true, message: '请设置答案正确答案'}]}>
                      <Select>
                        <Select.Option key={0} value={1}>正确</Select.Option>
                        <Select.Option key={1} value={0}>错误</Select.Option>
                      </Select>
                    </Form.Item>
                    :
                    <Form.Item
                      name='answer'
                      label='正确答案'
                      rules={[{required: true, message: '请设置答案正确答案'}]}>
                      <Input/>
                    </Form.Item>
                )
            }

            <Form.Item name='analyzing' label='试题解析'>
              <TextArea/>
            </Form.Item>

            <Form.Item style={{float: 'right'}}>
              <Space>
                <Button type='default' onClick={() => this.setState({editorVisible: false})}>取消</Button>
                <Button type='primary' htmlType='submit'>确定</Button>
              </Space>
            </Form.Item>
          </Form>
          }
        </Modal>
      </div>
    );
  }
}

export default connect()(QuestionManager);
